﻿using System;
using System.Collections;
using System.Net;

namespace HoNSharp
{
    public delegate void HoNClientRequesterCompletedEventHandler(object sender, HoNClientRequesterEventArgs e);

    public class HoNClientRequesterEventArgs : EventArgs
    {
        private Hashtable data;

        public HoNClientRequesterEventArgs(Hashtable info)
        {
            this.data = info;
        }

        public Hashtable Data()
        {
            return this.data;
        }
    }

    public class HoNClientRequester
    {
        public event HoNClientRequesterCompletedEventHandler onClientRequesterCompleted;

        protected virtual void OnClientRequest(HoNClientRequesterEventArgs e)
        {
            if (onClientRequesterCompleted != null)
            {
                onClientRequesterCompleted(this, e);
            }
        }

        private WebClient _wc;
        private string _func;
        private string _val;

        private void ReceivedClientRequesterData(Object sender, UploadDataCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                byte[] result = (byte[])e.Result;
                Hashtable info;
                try
                {
                    info = (Hashtable)PHPSerializer.UnSerialize(result);
                    info["__func__"] = this._func;
                    info["__index__"] = this._val;
                }
                catch (Exception)
                {
                    info = new Hashtable();
                    info["__func__"] = "failed";
                    info["__index__"] = this._val;
                }
                this.OnClientRequest(new HoNClientRequesterEventArgs(info));
            }
        }

        public HoNClientRequester(string func, string index, string postData)
        {
            this._func = func;
            this._val = index;
            this._wc = new WebClient();
            byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
            this._wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            this._wc.UploadDataCompleted += new UploadDataCompletedEventHandler(ReceivedClientRequesterData);
            this._wc.UploadDataAsync(new Uri("http://masterserver.hon.s2games.com/client_requester.php"), data);
            System.Diagnostics.Debug.WriteLine(postData);
        }
    }
}
